package com.aranandroid.customview.fragment

import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.core.view.children
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.aranandroid.customview.R

open class FragmentBase(context: Context?, attrs: AttributeSet?, fragmentLayoutId: Int) :
    LinearLayout(context, attrs) {

    var view: View

    var radio: RadioGroup


    var viewPager: ScrollControlViewPager

    var fmTemp: FragmentManager? = null

    var changeItme: (group: RadioGroup, checkedId: Int) -> Unit = { group, checkedId -> }

    var fragments: LinkedHashMap<Int, Fragment>? = null
        set(value) {
            field = value
            radioChange(radio)
        }


    var offscreenPageLimit = 3

    init {
        view = LayoutInflater.from(context).inflate(fragmentLayoutId, this, true)
        radio = view.findViewById(R.id.radio)
        viewPager = view.findViewById(R.id.pager)

        val obtainStyledAttributes = context?.obtainStyledAttributes(attrs, R.styleable.FragmentTop)
        obtainStyledAttributes?.let {
            viewPager.DISABLE = it.getBoolean(R.styleable.FragmentTop_scroll_control1, true)
            viewPager.ISSCROLL = it.getBoolean(R.styleable.FragmentTop_is_scroll_view, false)
            offscreenPageLimit = it.getInteger(R.styleable.FragmentTop_offscreenPageLimit, offscreenPageLimit)
        }
        obtainStyledAttributes?.let {
            radio.setBackgroundColor(
                it.getColor(
                    R.styleable.FragmentBottom_button_color,
                    context.resources.getColor(R.color.cardview_light_background)
                )
            )
        }
        obtainStyledAttributes?.recycle()
    }


    override fun dispatchDraw(canvas: Canvas?) {

        super.dispatchDraw(canvas)
        val children = children

        changeChildView(children)
    }

    /**
     * 调整子view 的位置
     * 当有RadioGroup时候直接吧 RadioGroup放到按钮位置（layout中；自己RadioGroup不显示）
     * 当没有RadioGroup  循环把RadioButton放到自己的RadioGroup中（layout不显示）
     */
    private fun changeChildView(children: Sequence<View>) {
        for (child in children) {
            if (child is RadioGroup) {
                (child.parent as ViewGroup).removeViewInLayout(child)
                (view?.findViewById(R.id.lin_group) as ViewGroup).addView(child)
                radioChange(child)
            } else {
                if (child is RadioButton) {
                    (child.parent as ViewGroup).removeViewInLayout(child)
                    radio.addView(child)
                    changeChildView(children)
                    break
                }
            }
        }
    }


    class MyFragmentPagerAdapter(
        fm: FragmentManager?,
        list: List<Fragment>
    ) :
        FragmentPagerAdapter(fm!!, FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
        private val listfragment //创建一个List<Fragment>
                : List<Fragment>

        override fun getItem(arg0: Int): Fragment {
            return listfragment[arg0] //返回第几个fragment
        }

        override fun getCount(): Int {
            return listfragment.size //总共有多少个fragment
        }

        // 定义构造带两个参数
        init {
            listfragment = list
        }
    }

    /**
     * 点击事件
     */
    private fun radioChange(radio: RadioGroup) {
        radio.setOnCheckedChangeListener({ group, checkedId ->
            fragments?.keys?.let {
                for ((i, key) in it.withIndex()) {
                    if (checkedId == key) {
                        viewPager.setCurrentItem(i, true)
                    }
                }
            }
            changeItme(group, checkedId)
        })
        var fm: FragmentManager? = null
        fmTemp?.let {
            fm = it
        } ?: let {
            if(context is FragmentActivity){
                fm = (context as FragmentActivity).getSupportFragmentManager()
            }

        }
        fm?.executePendingTransactions()
        val myFragmentPagerAdapter =
            fragments?.values?.toList()
                ?.let { MyFragmentPagerAdapter(fm, it) } //new myFragmentPagerAdater记得带上两个参数
        viewPager.adapter = myFragmentPagerAdapter
        viewPager.offscreenPageLimit = offscreenPageLimit
        viewPager.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionoffsetpixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
                fragments?.keys?.let {
                    for ((i, key) in it.withIndex()) {
                        if (position == i) {
                            radio.findViewById<RadioButton>(key)?.isChecked = true
                        }
                    }
                }
            }
        })
    }

}